package cn.csg.ams.collect2.poptopics.task;

import cn.csg.ams.collect2.poptopics.dao.MkMcTermAlarmLogDao;
import cn.csg.ams.collect2.poptopics.dataHandle.OutgaeAndRecover;
import cn.csg.ams.collect2.poptopics.entity.RecordInfo;
import cn.csg.ams.collect2.poptopics.infrastructure.constant.UserCategoryConstant;
import cn.csg.ams.collect2.poptopics.infrastructure.utils.RedisLockUtil;
import cn.hutool.core.map.MapUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 计划与故障工单复电任务, 每半个小时执行一次
 */
@Component
public class WorkOrderRecoverTask {

    private static Logger logger = LoggerFactory.getLogger(WorkOrderRecoverTask.class);

    @Autowired
    private RedisLockUtil redisLockUtil;

    @Autowired
    private MkMcTermAlarmLogDao termAlarmLogDao;

    @Autowired
    private OutgaeAndRecover outgaeAndRecover;

    // @Scheduled(cron = "0 0/30 * * * ?")
    public void workOrderRecoverTask() {
        // 由于多节点部署，需要保证每次只有一个节点执行
        String key = "fbs_work_order_recover";
        String requestId = UUID.randomUUID().toString();
        boolean lock = redisLockUtil.lock(key, requestId, 120 * 1000);
        if (!lock) {
            logger.info("该节点未抢到锁，跳过计划与故障工单复电任务");
            return;
        }

        // 执行线路停电任务
        logger.info("节点抢到锁, 开始执行计划与故障工单复电任务.............");
        workOrderRecover();
    }


    private void workOrderRecover() {
        // 查询关联了计划与故障工单，且还在停电，但工单已经复电的台区与复电时间
        List<Map<String, Object>> taRecoverTimeList = termAlarmLogDao.getWorkOrderRecoverTime();

        for (Map<String, Object> data : taRecoverTimeList) {
            // 地区编码
            String areaCode = MapUtil.getStr(data, "area_code");
            // 台区编号
            String taNo = MapUtil.getStr(data, "ta_no");
            // 复电时间
            String outageEndTime = MapUtil.getStr(data, "outage_end_time");
            // 复电来源 (3-计划， 4-故障 )
            String restoreSource = MapUtil.getStr(data, "restore_source");

            // 给台区复电
            RecordInfo recordInfo = new RecordInfo();
            recordInfo.setUserType(UserCategoryConstant.PUBLIC_TA);
            recordInfo.setAreaCode(areaCode);
            recordInfo.setTaNo(taNo);
            outgaeAndRecover.taReCover(outageEndTime, recordInfo, restoreSource, System.currentTimeMillis());
        }
    }

}
